/**
  ******************************************************************************
  * @file    mg_test_ble.c
  * @author  
  * @version V1.1
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT 2020 Shanghai Macrogiga Electronics</center></h2>
  *
  ******************************************************************************
  */
#include "mg_driver.h"
#include "mg_ble_control.h"



void toggle_led(void)
{
    static char high = 0;
    
    if(high)GPIO->DATA_OUT_SET = GPIO_PIN_10;
    else GPIO->DATA_OUT_CLEAR = GPIO_PIN_10;
    
    high = !high;
}

void init_led(void)
{
    GPIO_InitTypeDef cfg;
    
    GPIO_FunctionSelect(GPIO_MAP_PIN_A10,GPIO_MAP_PIN_FUNC3);
    
    cfg.GPIO_Mode = GPIO_Mode_Out_PP;
    cfg.GPIO_Pin  = GPIO_PIN_10;
    GPIO_Init(GPIO, &cfg);

    GPIO_ResetBits(GPIO, GPIO_PIN_10); //L = led_on
}


static u8 adv[] = {2,BLE_GAP_AD_TYPE_FLAGS,4,
                   26,BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, 0x4C,0x00, 0x02,0x15, 0xFD,0xA5,0x06,0x93,0xA4,0xE2,0x4F,0xB1,0xAF,0xCF,0xC6,0xEB,0x07,0x64,0x78,0x25, 0x27,0x32, 0x52,0xB0, 0xCA};
static u8 rsp[] = {10,BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME,'m','g','i','b','e','a','c','o','n'};

////// !!! porting function, this will be invoked by ble lib. !!!/////
void slave_app_cfg(void)
{
    BLE_ADV_DATA_INFO slave_cfg;
    
    slave_cfg.advType = ADV_NONCONN_IND;//ADV_NONCONN_IND;//ADV_IND;//ADV_SCAN_IND//ADV_DIRECT_IND
    slave_cfg.advData = adv;
    slave_cfg.advDataLen = sizeof(adv);    
    slave_cfg.scanResponseData= rsp;    
    slave_cfg.scanResponseDataLen = sizeof(rsp);
    slave_cfg.interval = 200; //200*0.625=125 ms
    slave_cfg.txAddrType = 1;
    slave_cfg.directIndTargetAddr[0] = 0; //target addr if any
    slave_cfg.directIndTargetAddr[1] = 0;
    slave_cfg.directIndTargetAddrType = 1;

    MgBle_Periph_Init(&slave_cfg);
}

void test_ble_iBeacon(void)
{
    u8 *ble_addr;
    
    init_led(); //LED indication
    
    //================== BLE Base band init ================
    MgBle_Init(TXPWR_0DBM, &ble_addr);
    
    //============ clear MCU pending irq if any ============
    NVIC_IrqClearPendingIRQ(BBSeg_IRQn);
    NVIC_IrqClearPendingIRQ(BB_IRQn);
    
    //============== Enable NVIC IRQ bits ==================
    NVIC_EnableIRQ(INT_MASK_BIT_BB);
    
    //================== BLE Slave role init ===============
    slave_app_cfg(); //cfg the slave
    
    //================ BLE Slave stack running =============
    while(1)
    {
        //*** user task inserted here ***
        //to do...
        
        SysGotoStopMode(); //MCU goto power saving mode
    }
    
    //never be here
}
